using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Xml;
using DataScripter.Containers;
using DataScripter.Scripting.ProcessDefinitions;
using DataScripter.Scripting.Processes;

namespace DataScripter.XmlInterpreter.XmlInterpreters
{
    internal class ProcessDefinitionInterpreter : IXmlInterpreter<IProcessDefinition>
    {
        public IContainer Container { get; set; }
        private IProcessDefinition ProcessDefinition { get; set; }

        public ProcessDefinitionInterpreter(IContainer engine)
        {
            Container = engine;
        }

        public IProcessDefinition InterpretElement(XmlElement element)
        {
            string name = element.GetAttribute("Name");
            ProcessDefinition = new ProcessDefinition(name, Container);

            foreach (XmlElement child in element.ChildNodes.OfType<XmlElement>())
            {
                switch (child.Name)
                {
                    case "Process":
                        InterpretProcess(child);
                        break;
                }
            }
            return ProcessDefinition;
        }

        private void InterpretProcess(XmlElement element)
        {
            string processName = element.GetAttribute("Name");
            string processType = element.GetAttribute("Service");
            IProcess process = Container.Resolve<IProcess>(processType, new HybridDictionary { { "name", processName }, { "container", Container } });
            ProcessDefinition.AddProcess(processName, process);

            string input = element.GetAttribute("Input");
            if (input != string.Empty )
            {
                IProcess inputProcess = ProcessDefinition.GetProcessByName(input);
                process.AddDependency(inputProcess);
            }

            Dictionary<string, string> parameters = new Dictionary<string, string>();
            foreach (XmlElement childElement in element.ChildNodes.OfType<XmlElement>())
            {
                string name = childElement.GetAttribute("Name");
                parameters.Add(childElement.Name, name);
            }
            process.Initialize(parameters);
        }
    }
}